<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>通讯录</title>
    <style>
        h1{ color:red;}
        input{
            padding: 8px;
            border-radius: 6px;
            margin: 5px 0;
        }
        .errMsg{
            color: red;
            font-weight: bold;
        }
    </style>

</head>
<body><?php
try{
    $db=new PDO('mysql:host=localhost;dbname=db','root','12qwas');
    if($_POST){//若提交有数据
        $xh=$_POST['xh'];
        $name=$_POST['name'];
        $tel=$_POST['tel'];
        if($_GET['xh']) { //要修改用户信息
            $ps = $db->prepare("update students set xh=?,name=?,tel=? where xh=?");
            $ps->execute(array($xh, $name, $tel, $_GET['xh']));
        }else{ //创建新用户，此时需要插入一条新的记录
            $ps = $db->prepare("insert into students (xh,name,tel) values (?,?,?)");
            $ps->execute(array($xh, $name, $tel));
        }
        header("location:index.php");//重定向到首页
        return;
    }else if($_GET['xh']) {//要修改用户信息，需要把用户原来的信息显示表单中，便于用户直接修改
        $ps = $db->prepare("select * from students where xh=?");
        $ps->execute(array($_GET['xh']));
        $r = $ps->fetch(PDO::FETCH_ASSOC);
        if ($r) {
            $xh = $r['xh'];
            $name = $r['name'];
            $tel = $r['tel'];
        }
    }
}catch(Throwable $e){
    $errMsg=$e->getMessage();
}
?>
<h1><?=$_GET["xh"]?'修改用户信息':'创建新用户'?></h1>
<form method="post">
    学号：<input type="text" name="xh" value="<?=htmlentities($xh??'')?>" /><br>
    姓名：<input type="text" name="name" value="<?=htmlentities($name??'')?>" /><br>
    电话：<input type="text" name="tel" value="<?=htmlentities($tel??'')?>" /><br>
    <div class="errMsg"><?=htmlentities($errMsg??'')?></div>
    <input type="submit" value=" <?=$_GET['xh']?'修改用户信息':'创建新用户'?> " /><br>
</form>
</body>
</html>
